<template>
  <div class="detail-table">
    <div class="detail-title">
      <i class="el-icon-s-grid" />
      <span>{{ type }}-订单排程</span>
    </div>
    <mes-table
      style="padding: 0px 10px 10px"
      ref="editTable1"
      :columns="columns"
      :max-height="270"
      :index="true"
      :tableData="rows"
      :pagination-hide="true"
      :ck="false"
    ></mes-table>
    <MesBox
      title="生成工序计划"
      v-model="showSendModal"
      :lazy="true"
      :width="1300"
      :height="600"
    >
      <!-- <MesForm
        :formRules="BusinessFormRules"
        :formFields="BusinessFormFields"
      ></MesForm> -->
      <MesHeader title="待生成计划列表">
        <!-- <template #default>
          <el-button size="small" link class="textColor" @click="addRow"
            ><i class="el-icon-plus" style="margin-right: 5px"></i
            >添加行</el-button
          >
          <el-button size="small" link class="textColor" @click="delRow"
            ><i class="el-icon-minus" style="margin-right: 5px"></i
            >删除行</el-button
          >
        </template> -->
      </MesHeader>
      <MesTable
        ref="planList"
        :columns="sendFormColumns"
        :loadKey="true"
        :clickEdit="true"
        :tableData="tableData"
        :index="true"
      ></MesTable>
      <template #footer>
        <el-button type="success" @click="saveData">
          <i class="el-icon-success" style="margin-right: 5px"></i>
          保存</el-button
        >
        <el-button type="danger" @click="cancel">
          <i class="el-icon-error" style="margin-right: 5px"></i>
          取消</el-button
        >
      </template>
    </MesBox>

    <MesBox
      v-model="reworkVisible"
      title="生成返工工单"
      :width="1000"
      :height="300"
    >
      <MesForm
        ref="reworkForm"
        :formFields="formFields"
        :formRules="formRules"
      ></MesForm>
      <template #footer>
        <el-button type="danger" @click="createReworkOrder">
          <i class="el-icon-check"></i>
          保存
        </el-button>
      </template>
    </MesBox>

    <el-dialog v-model="dialogVisible" title="提示" width="50%">
      <div v-html="tips"></div>
      <template #footer>
        <span class="dialog-footer">
          <!-- <el-button @click="closeDialog">否</el-button> -->
          <el-button type="primary" @click="makeBuying"> 是 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import MesTable from '@/components/basic/MesTable.vue'
import MesBox from '@/components/basic/MesBox.vue'
import MesForm from '@/components/basic/MesForm.vue'
import MesHeader from '@/components/basic/MesHeader.vue'
import { getNowDate } from '@/uitils/dateFormatUtil'
import { ElMessageBox } from 'element-plus'

export default {
  emits: ['parentCall'],
  components: { MesTable, MesBox, MesForm, MesHeader },
  data() {
    return {
      columns: [
        {
          title: '操作',
          field: 'action',
          width: 350,
          render: (h, { row }) => {
            let { permission } = this.$store.getters.getPermission(
              '/Production_SalesOrder'
            )
            let dom1 = ''
            let dom2 = ''
            let dom3 = ''
            if (permission.includes('createWorkOrder')) {
              if (row.SalesOrderStatus !== 3) {
                dom1 = (
                  <el-link
                    underline={false}
                    type="primary"
                    onClick={async () => {
                      this.showSendModal = true
                      let { SalesOrderList_Id } = row
                      let res = await this.http.post(
                        'api/Production_SalesOrder/GetWorkOrderList?Id=' +
                          SalesOrderList_Id,
                        null,
                        true
                      )
                      {
                        /* console.log(res) */
                      }
                      this.tableData = res.map((item) => {
                        return {
                          ...item,
                          qty: item.estimateQty,
                          startTime: getNowDate(),
                        }
                      })
                    }}
                  >
                    <i class="el-icon-news"></i>
                    生成工序计划
                  </el-link>
                )
              }
            }

            // if (permission.includes('BusinessScheduling')) {
            //   dom1 = (
            //     <el-link
            //       underline={false}
            //       type="primary"
            //       onClick={() => this.BusinessScheduling(row)}
            //     >
            //       <i class="el-icon-news"></i>
            //       业务排单
            //     </el-link>
            //   )
            // }

            // if (permission.includes('createReworkOrder')) {
            //   dom2 = (
            //     <el-link
            //       underline={false}
            //       type="primary"
            //       onClick={async () => {
            //         this.reworkVisible = true
            //         {
            //           /* console.log(row) */
            //         }
            //         this.formFields.moCode = row.MoCode
            //         this.formFields.productCode = row.ProductCode
            //         this.formFields.productName = row.ProductName
            //         this.formFields.productStandard = row.ProductStandard
            //       }}
            //       style="margin-left: 10px"
            //     >
            //       <i class="el-icon-sold-out"></i>
            //       生成返工工单(客退)
            //     </el-link>
            //   )
            // }

            if (permission.includes('closeMom')) {
              if (row.SalesOrderStatus !== 3) {
                dom3 = (
                  <el-link
                    underline={false}
                    type="primary"
                    style="margin-left: 10px"
                    onClick={async () => {
                      try {
                        await ElMessageBox.confirm(
                          '确定要强制结案吗?',
                          'Warning',
                          {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                          }
                        )

                        const res = await this.http.post(
                          `/api/Production_WorkOrder/ClosedMom?Id=${row.SalesOrderList_Id}`,
                          null,
                          true
                        )
                        if (res.status) {
                          this.$message.success('结案成功')
                          this.$emit('parentCall', ($parent) => {
                            $parent.search()
                          })
                        } else {
                          this.$message.error(res.message)
                        }
                      } catch (error) {
                        console.log(error)
                      }
                    }}
                  >
                    <i class="el-icon-circle-close"></i>
                    强制结案
                  </el-link>
                )
              }
            }
            return h('div', null, [dom1, dom2, dom3])
          },
        },
        {
          title: '客户编码',
          field: 'CusCode',
          width: 120,
        },
        {
          title: '客户名称',
          field: 'CusName',
          width: 120,
        },
        {
          field: 'SalesOrderList_Id',
          title: '销售订单产品明细表主键ID',
          type: 'int',
          width: 110,
          hidden: true,
          readonly: true,
          require: true,
          align: 'left',
        },
        {
          field: 'SalesOrder_Id',
          title: '销售订单',
          type: 'int',
          width: 110,
          hidden: true,
          readonly: true,
          require: true,
          align: 'left',
        },
        {
          field: 'ProductCode',
          title: '产品编号',
          type: 'string',
          sort: true,
          width: 180,
          readonly: true,
          require: true,
          align: 'left',
          sort: true,
        },
        {
          field: 'ProductName',
          title: '产品名称',
          type: 'string',
          sort: true,
          width: 180,
          readonly: true,
          require: true,
          align: 'left',
        },
        {
          field: 'ProductStandard',
          title: '产品规格',
          type: 'string',
          width: 180,
          readonly: true,
          align: 'left',
        },
        {
          field: 'MoCode',
          title: '排程编号',
          type: 'string',
          width: 180,
          readonly: true,
          align: 'left',
        },
        {
          field: 'Qty',
          title: '数量',
          type: 'int',
          width: 110,
          require: true,
          align: 'left',
        },
        {
          field: 'FinishQty',
          title: '良品数',
          type: 'int',
          width: 110,
          readonly: true,
          align: 'left',
        },
        {
          field: 'NgGoodQty',
          title: '不良数',
          type: 'int',
          width: 110,
          readonly: true,
          align: 'left',
        },
        {
          field: 'ScrapQty',
          title: '报废数',
          type: 'int',
          width: 110,
          readonly: true,
          align: 'left',
        },
        { 
          field: 'PaidQty',
          title: '已交数量',
          type: 'int',
          width: 110,
          readonly: true,
          align: 'left',
        },
        { 
          field: 'UnpaidQty',
          title: '未交数量',
          type: 'int',
          width: 110,
          readonly: true,
          align: 'left',
        },
        {
          field: 'SalesOrderStatus',
          title: '状态',
          type: 'int',
          width: 110,
          readonly: true,
          align: 'left',
          formatter(row, column, event) {
            switch (row.SalesOrderStatus) {
              case 1:
                return '<span class="el-tag el-tag--default el-tag--light">未开始</span>'
              case 2:
                return '<span class="el-tag el-tag--default el-tag--light">进行中</span>'
              case 3:
                return '<span class="el-tag el-tag--default el-tag--light">已完成</span>'
              default:
                return ''
            }
          },
        },
        {
          field: 'CreateDate',
          title: '创建时间',
          type: 'datetime',
          width: 110,
          align: 'left',
          sort: true,
        },
        {
          field: 'CreateID',
          title: '创建人编号',
          type: 'int',
          width: 80,
          hidden: true,
          align: 'left',
        },
        {
          field: 'Creator',
          title: '创建人',
          type: 'string',
          width: 130,
          align: 'left',
        },
        {
          field: 'Modifier',
          title: '修改人',
          type: 'string',
          width: 130,
          align: 'left',
        },
        {
          field: 'ModifyDate',
          title: '修改时间',
          type: 'datetime',
          width: 110,
          align: 'left',
          sort: true,
        },
        {
          field: 'ModifyID',
          title: '修改人编号',
          type: 'int',
          width: 80,
          hidden: true,
          align: 'left',
        },
        {
          field: 'Product_Id',
          title: '产品ID',
          type: 'int',
          width: 110,
          hidden: true,
          readonly: true,
          require: true,
          align: 'left',
        },
        {
          field: 'PlanStartDate',
          title: '计划开始时间',
          type: 'datetime',
          width: 110,
          readonly: true,
          require: true,
          align: 'left',
        },
        {
          field: 'PlanEndDate',
          title: '计划结束时间',
          type: 'datetime',
          width: 110,
          readonly: true,
          require: true,
          align: 'left',
        },
        {
          field: 'ActualStartDate',
          title: '实际开始时间',
          type: 'datetime',
          width: 110,
          readonly: true,
          require: true,
          align: 'left',
        },
        {
          field: 'ActualEndDate',
          title: '实际结束时间',
          type: 'datetime',
          width: 110,
          readonly: true,
          require: true,
          align: 'left',
        },
      ],
      BusinessFormRules: [
        [
          {
            title: '产品名称',
            field: 'ProductName',
            disabled: true,
          },
          {
            title: '产品编码',
            field: 'ProductCode',
            disabled: true,
          },
          {
            title: '产品规格',
            field: 'ProductStandard',
            disabled: true,
          },
        ],
        [
          {
            title: '客户编码',
            field: 'CusCode',
            disabled: true,
          },
          {
            title: '客户名称',
            field: 'CusName',
            disabled: true,
          },
          {
            title: '订单号',
            field: 'MoCode',
            disabled: true,
          },
        ],
        [
          {
            title: '订单数量',
            field: 'Qty',
            disabled: true,
          },
          {
            title: '计划开始时间',
            field: 'PlanStartDate',
            disabled: true,
          },
          {
            title: '计划结束时间',
            field: 'PlanEndDate',
            disabled: true,
          },
        ],
        [
          {
            title: 'SalesOrderList_Id',
            field: 'SalesOrderList_Id',
            hidden: true,
          },
        ],
      ],
      BusinessFormFields: {
        ProductName: '',
        ProductCode: '',
        ProductStandard: '',
        CusCode: '',
        CusName: '',
        MoCode: '',
        Qty: 0,
        PlanStartDate: '',
        PlanEndDate: '',
        SalesOrderList_Id: '',
      },
      rows: [],
      type: '',
      showSendModal: false,
      sendFormColumns: [
        {
          field: 'productCode',
          title: '产品编码',
          showOverflowTooltip: true,
        },
        {
          field: 'productName',
          title: '产品名称',
          showOverflowTooltip: true,
        },
        {
          field: 'estimateQty',
          title: '可拆数量',
          showOverflowTooltip: true,
        },
        {
          field: 'qty',
          title: '计划数量',
          render: (h, { row }) => {
            // console.log(row);
            return (
              <el-input-number
                v-model={row.qty}
                min={0}
                max={row.estimateQty}
              />
            )
          },
        },
        {
          field: 'putQty',
          title: '入库数量',
          showOverflowTooltip: true,
        },
        {
          title: '计划开始时间',
          field: 'startTime',
          required: true,
          edit: {
            type: 'datetime',
          },
        },
        {
          title: '计划结束时间',
          field: 'endTime',
          required: true,
          edit: {
            type: 'datetime',
          },
        },
      ],
      // sendFormColumns: [
      //   {
      //     title: '计划数量',
      //     field: 'qty',
      //     required: true,
      //     min: 0,
      //     edit: {
      //       type: 'number',
      //     },
      //   },
      //   {
      //     title: '计划开始时间',
      //     field: 'planStartDate',
      //     required: true,
      //     edit: {
      //       type: 'datetime',
      //     },
      //   },
      //   {
      //     title: '计划结束时间',
      //     field: 'planEndDate',
      //     required: true,
      //     edit: {
      //       type: 'datetime',
      //     },
      //   },
      //   {
      //     title: '交付日期',
      //     field: 'deliveryDate',
      //     required: true,
      //     edit: {
      //       type: 'datetime',
      //     },
      //   },
      // ],
      tableData: [],
      dialogVisible: false,
      tips: '',
      params: [],
      reworkVisible: false,
      formFields: {
        moCode: '',
        process_Id: null,
        qty: 0,
        startTime: getNowDate(),
        endTime: '',
        productName: '',
        productCode: '',
        productStandard: '',
      },
      formRules: [
        [
          {
            title: '订单号',
            field: 'moCode',
            readonly: true,
          },
          {
            title: '产品名称',
            field: 'productName',
            readonly: true,
          },
        ],
        [
          {
            title: '产品编码',
            field: 'productCode',
            readonly: true,
          },
          {
            title: '产品规格',
            field: 'productStandard',
            readonly: true,
          },
        ],
        [
          {
            title: '工艺路线',
            field: 'process_Id',
            required: true,
            type: 'select',
            dataKey: 'reworkProcessList',
          },
          {
            title: '数量',
            field: 'qty',
            required: true,
            type: 'number',
            min: 0,
          },
        ],
        [
          {
            title: '计划开始时间',
            field: 'startTime',
            required: true,
            type: 'datetime',
          },
          {
            title: '计划结束时间',
            field: 'endTime',
            required: true,
            type: 'datetime',
          },
        ],
      ],
    }
  },
  methods: {
    rowClick(row, type) {
      this.type = type
      let url = ''
      // console.log(type)
      switch (type) {
        case '销售订单':
          url =
            'api/Production_SalesOrder/getDetailRows?SalesOrder_Id=' +
            row.SalesOrder_Id
          break
        case '生产计划':
          url =
            'api/Production_ProductPlan/getDetailRows?ProductPlan_Id=' +
            row.ProductPlan_Id
          break
        default:
          //这里是没有找到对应的值处理
          break
      }
      this.http.get(url, {}, true).then((rows) => {
        this.rows = rows
      })
    },
    //保存
    async saveData() {
      let planList = this.$refs.planList.getSelected()
      if (planList.length) {
        let { SalesOrderList_Id } = this.rows[0]
        let url =
          '/api/Production_WorkOrder/CreateWorkChildren?Id=' + SalesOrderList_Id

        let findSelect = planList.find(
          (item) => !item.qty || !item.startTime || !item.endTime
        )
        if (findSelect == undefined) {
          this.params = planList
          let param = {
            childmodels: planList,
          }

          this.http.post(url, param, true).then((res) => {
            if (res.status) {
              this.$message.success('创建成功')
              this.tableData = []
              this.showSendModal = false
              this.rowClick(this.rows[0], '销售订单')
            } else {
              this.tips = ''
              let msg = res.message.split('\n')
              msg.forEach((item) => (this.tips += `<div>${item}<div>`))
              // console.log(this.tips)
              this.dialogVisible = true
            }
          })
        } else {
          this.$message.error('请填写完整信息')
        }
      } else {
        this.$message.error('至少添加一项计划才能生成')
      }

      // if (this.tableData.length) {
      //   const findSelect = this.tableData.find(
      //     (item) =>
      //       !item.qty ||
      //       !item.planStartDate ||
      //       !item.planEndDate ||
      //       !item.deliveryDate
      //   )
      //   if (findSelect == undefined) {
      //     const id = this.BusinessFormFields.SalesOrderList_Id
      //     const childrenlist = this.tableData
      //     const res = await this.http.post(
      //       '/api/Production_WorkOrder/CreateChildRenOrder11',
      //       { id, childrenlist },
      //       true
      //     )
      //     if (res.status) {
      //       this.$message.success('创建计划成功')
      //       this.cancel()
      //       this.$emit('parentCall', ($parent) => {
      //         $parent.search()
      //       })
      //     } else {
      //       this.$message.error(res.message)
      //     }
      //   } else {
      //     this.$message.error('请填写完整信息')
      //   }
      // } else {
      //   this.$message.error('至少添加一项计划才能生成')
      // }
    },
    //取消
    cancel() {
      this.showSendModal = false
      this.$refs.planList.reset() //表单重置
      this.tableData = []
    },
    // 生成请购单
    async makeBuying() {
      let { SalesOrderList_Id } = this.rows[0]
      let url =
        '/api/Production_WorkOrder/CheckCreateWorkChildren?Id=' +
        SalesOrderList_Id
      let param = {
        childmodels: this.params,
      }
      let res = await this.http.post(url, param, true)
      if (res.status) {
        this.$message.success('成功生成缺料清单')
        this.closeDialog()
        this.cancel()
      } else {
        this.$message.error(res.message)
      }
    },
    // 关闭dialog
    closeDialog() {
      this.tips = ''
      this.dialogVisible = false
    },
    //生成返工工单
    createReworkOrder() {
      this.$refs.reworkForm.validate(async (valid) => {
        if (valid) {
          let res = await this.http.post(
            '/api/Production_WorkOrder/CreateReWorkOrder',
            this.formFields,
            true
          )

          if (res.status) {
            this.$message.success('创建成功')
            this.reworkVisible = false
            this.$emit('parentCall', ($parent) => {
              $parent.search()
            })
            this.formFields = {
              moCode: '',
              process_Id: null,
              qty: 0,
              startTime: getNowDate(),
              endTime: '',
              productName: '',
              productCode: '',
              productStandard: '',
            }
          } else {
            this.$message.error(res.message)
          }
        }
      })
    },
    BusinessScheduling(row) {
      this.showSendModal = true
      for (const key in this.BusinessFormFields) {
        this.BusinessFormFields[key] = row[key]
      }
    },
    addRow() {
      this.tableData.push({
        qty: 0,
        planStartDate: getNowDate(),
        planEndDate: '',
        deliveryDate: '',
      })
    },
    delRow() {
      this.$refs.planList.delRow()
    },
  },
}
</script>

<style lang="less" scoped>
.detail-table {
  padding: 0px 4px;
  border-top: 10px solid rgb(238, 238, 238);
  h3 {
    font-weight: 500;
    padding-left: 10px;
    background: #fff;
    margin-top: 8px;
    padding-bottom: 5px;
  }
}
.detail-title {
  padding: 10px;
  font-size: 15px;
  color: '#313131';
  font-weight: bold;
}
</style>
